<template>
  <div>
    <!-- 头部栏 -->
    <van-nav-bar
      :title="isEdit?'收货地址编辑':'添加地址'"
      left-text="返回"
      left-arrow
      @click-left="router.back()"
    />
    <van-address-edit
      :address-info="editAddress"
      :area-list="areaList"
      show-set-default
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
    />
  </div>
</template>
  
<script setup>
import { ref,onMounted } from "vue";
// 省市区数据
import { areaList } from "@vant/area-data";
import { useRouter,useRoute } from "vue-router";
import { showSuccessToast } from "vant";
// 收获地址相关接口
import { addAddress,getAddressList,updateAddress } from "@/api/address";

let router = useRouter();
let route=useRoute();

// 要回溯的编辑数据
let editAddress=ref({})
// 判断是否编辑状态的标识
let isEdit=ref(route.query.id?true:false)
// 保存还是编辑
let onSave = async (value) => {
  // 改变数据字段传给后端
  let data = {
    is_default: value.isDefault ? "1" : "0",
    name: value.name,
    phone: value.tel,
    province: value.province,
    city: value.city,
    town: value.county,
    street: '默认值',
    detail: value.addressDetail,
  };
  if(isEdit.value){
    // 编辑
    await updateAddress({...data,id:route.query.id});
    showSuccessToast('编辑地址成功');
  }else{
    await addAddress(data);
    showSuccessToast('添加地址成功');
  }
  router.back('/address-list');
};

onMounted(async()=>{
  // 判断是否是要编辑
  if(isEdit.value){
    let res=(await getAddressList({limit:100,page:1})).list;
    // 要编辑的那一条数据 filter返回的是一个数组
    let editAddressData=res.filter(item=>item.id==route.query.id);
    // 后端返回的数据 改造为组件需要的数据
    editAddress.value={
      id:editAddressData[0].id,
      name:editAddressData[0].name,
      tel:editAddressData[0].phone,
      province:editAddressData[0].province,
      county:editAddressData[0].town,
      city:editAddressData[0].city,
      addressDetail:editAddressData[0].detail,
      isDefault:!!editAddressData[0].is_default
    }
  }
})



</script>
  
<style scoped lang="less">
</style>